package com.woniu.utils;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;

/**
 * @Author pml
 * @Date 2025/6/18 23:08
 * @Description TODO
 * IP地址工具类
 * 从请求中提取客户端真实IP，支持代理场景
 */
public class IpUtils {
    public static String getIpAddress(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        // 优先从X-Forwarded-For获取（代理场景）
        String ip = request.getHeaders().getFirst("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("WL-Proxy-Client-IP");
        }
        // 最后从请求地址获取
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddress() != null ?
                    request.getRemoteAddress().getAddress().getHostAddress() : "unknown";
        }
        // 处理多代理情况，取第一个IP
        if (ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }
}
